const cloud = require('wx-server-sdk');
const db = cloud.database();
const _ = db.command;

/**
 * 工具函数：将对象的键从下划线命名转换为驼峰命名
 * @param {Object|Array} data - 需要转换的对象或数组
 * @returns {Object|Array} - 转换后的对象或数组
 */
const toCamelCase = (data) => {
  if (Array.isArray(data)) {
    return data.map((item) => toCamelCase(item));
  } else if (data && typeof data === "object") {
    return Object.keys(data).reduce((result, key) => {
      const camelKey = key.replace(/_([a-z])/g, (_, letter) =>
        letter.toUpperCase()
      );
      result[camelKey] = toCamelCase(data[key]);
      return result;
    }, {});
  } else {
    return data;
  }
};

// 工具函数：格式化日期为 YYYY-MM-DD HH:MM:SS
function formatDateToYY_MM_DD_HH_MM_SS(date) {
  const offset = 8 * 60; // UTC+8
  const localDate = new Date(date.getTime() + offset * 60 * 1000);

  const year = localDate.getUTCFullYear();
  const month = String(localDate.getUTCMonth() + 1).padStart(2, '0');
  const day = String(localDate.getUTCDate()).padStart(2, '0');
  const hours = String(localDate.getUTCHours()).padStart(2, '0');
  const minutes = String(localDate.getUTCMinutes()).padStart(2, '0');
  const seconds = String(localDate.getUTCSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 获取订单列表
 * @param {Object} request - 请求参数
 * @param {string} request.userId - 用户ID（必填）
 * @param {string} [request.orderId] - 订单ID（可选，用于查询单个订单）
 * @param {string} [request.orderStatus] - 订单状态（可选：inProgress/refunded/done）
 * @param {string} [request.processStatus] - 处理状态（可选）
 * @param {number} [request.page=1] - 页码
 * @param {number} [request.pageSize=100] - 每页条数
 * @returns {Promise<Object>} 返回订单列表数据
 * 
 * @description
 * - 通用条件：排除待支付订单 + 用户权限验证
 * - 可选条件：订单ID、订单状态、处理状态等筛选条件
 * - 所有条件在同一层级，无嵌套逻辑
 */

async function queryOrderByCondition(condition, page, pageSize, excludeProductFilterForTotal = false) {
  // 查询订单信息
  const orders = await db
    .collection("order")
    .where(condition)
    .orderBy("create_ts", "desc")
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .get();

  // 获取总条数（仅在未传入订单 ID 时计算总数）
  let total = 0;
  let totalCondition = condition;
  
  // 如果需要排除产品筛选来计算总数，则移除产品筛选条件
  if (excludeProductFilterForTotal && condition["order_item.product_id"]) {
    totalCondition = { ...condition };
    delete totalCondition["order_item.product_id"];
  }
  
  const totalResult = await db.collection("order").where(totalCondition).count();
  total = totalResult.total;
  

  // 转换时间格式
  const formattedOrders = orders.data.map((order) => {
    if (order.create_ts) {
      order.create_ts = formatDateToYY_MM_DD_HH_MM_SS(order.create_ts);
    }
    if (order.update_ts) {
      order.update_ts = formatDateToYY_MM_DD_HH_MM_SS(order.update_ts);
    }
    if (order.complaint_info && order.complaint_info.camplaint_time) {
      order.complaint_info.camplaint_time = formatDateToYY_MM_DD_HH_MM_SS(order.complaint_info.camplaint_time);
    }
    return order;
  });

  // 转换返回数据的字段为驼峰命名
  const camelCaseOrders = toCamelCase(formattedOrders);

  return {
    code: 200,
    message: "获取订单信息成功",
    data: {
      orders: camelCaseOrders,
      total: total,
      page: page,
      pageSize: pageSize,
    },
  };
}

async function getOrderList(request) {
  const {
    userId,
    orderId, // 新增：订单ID参数
    orderStatus,
    processStatus,
    page = 1,
    pageSize = 100,
  } = request;

  try {
    let condition = {};
    
    // 通用条件：排除待支付订单 + 用户权限验证
    condition.order_status = _.and([_.neq("待支付")]);
    condition.out_user_id = userId;
    
    // 可选条件（扁平化，无嵌套）
    if (orderId) {
      condition.order_id = orderId;
    }
    
    if (orderStatus === "inProgress") {
      condition.order_status = "已支付";
    }
    
    if (orderStatus === "refunded") {
      // 退款相关状态包括"已退款"、"部分退款"和"退款中"
      condition.order_status = _.in(["已退款", "部分退款", "退款中"]);
    }
    
    if (orderStatus === "done") {
      condition.order_status = "已完成";
    }
    
    if (processStatus) {
      condition.process_status = _.in(processStatus);
    }
    
    return queryOrderByCondition(condition, page, pageSize);
    
  } catch (error) {
    console.error("获取订单信息失败：", error);
    return {
      code: 500,
      message: "获取订单信息失败",
      data: null,
    };
  }
}

// 按订单ID查询订单详情 - 专门用于订单详情页面
async function getOrderForDetail(request) {
  const { orderId, page = 1, pageSize = 100 } = request;

  try {
    if (!orderId) {
      return {
        code: 400,
        message: "订单ID不能为空",
        data: null,
      };
    }

    // 按订单ID查询
    const condition = {
      order_id: orderId
    };

    return queryOrderByCondition(condition, page, pageSize);

  } catch (error) {
    console.error("获取订单详情失败：", error);
    return {
      code: 500,
      message: "获取订单详情失败",
      data: null,
    };
  }
}

async function getOrderListForManage(request) {
  let condition = {};
  const {
    userId,
    riderId,
    orderId,
    orderStatus,
    processStatus,
    orderType,
    noRiderId,
    hasRiderId, // 新增：已领取订单标识
    schoolCode,
    productId,
    startDate,
    endDate,
    excludeRefundedOrders = true, // 新增：是否排除退款订单，默认true
    page = 1,
    pageSize = 100,
  } = request;

  // 根据用户权限和学校过滤订单
  if (userId) {
    // 查询用户信息
    const userRes = await db.collection('user').where({ out_user_id: userId }).get();
    if (userRes.data.length > 0) {
      const userDoc = userRes.data[0];
      // 检查用户是否有学校权限限制
      if (userDoc.role_school && userDoc.role_school.length > 0 && !userDoc.role_school.includes('all')) {
        // 添加学校代码过滤条件
        condition['address.schoolCode'] = _.in(userDoc.role_school);
      }
    }
  }
  
  // 基础订单状态过滤：排除待支付订单
  condition.order_status = _.and([_.neq("待支付")]);
  
  // 根据参数决定是否排除退款订单
  if (excludeRefundedOrders) {
    condition.order_status = _.and([
      condition.order_status,
      _.neq("已退款"),
      _.neq("部分退款")
    ]);
  }
  
  // 添加订单状态筛选支持
  if (orderStatus) {
    switch (orderStatus) {
      case "inProgress":
        condition.order_status = "已支付";
        break;
      case "refunded":
        // 退款相关状态包括"已退款"、"部分退款"和"退款中"
        condition.order_status = _.in(["已退款", "部分退款", "退款中"]);
        break;
      case "done":
        condition.order_status = "已完成";
        break;
      default:
        // 如果传入的是具体的状态值，直接使用
        condition.order_status = orderStatus;
        break;
    }
  }
  
  // 添加处理状态筛选支持
  if (processStatus) {
    condition.process_status = _.in(processStatus);
  }
  
  if (orderType) {
    condition["order_item.product_id"] = orderType;
  }
  
  // 添加产品筛选支持
  if (productId) {
    condition["order_item.product_id"] = productId;
  }

  if (orderId) {
    // 场景 1: 扫码查询或者订单号查询
    condition.order_id = orderId;
  }

  if (riderId) {
    condition.deliver_out_user_id = riderId;
    // 移除退款状态过滤，由全局excludeRefundedOrders参数控制
  }

  if (noRiderId) {
    condition.deliver_out_user_id = _.or([
      _.eq(null),
      _.eq(""),
      _.eq(undefined)
    ]);
  }

  if (hasRiderId) {
    condition.deliver_out_user_id = _.and([
      _.neq(null),
      _.neq(""),
      _.neq(undefined)
    ]);
  }

  // 根据学校代码筛选订单
  if (schoolCode) {
    condition['address.schoolCode'] = schoolCode;
  }

  // 根据日期范围筛选订单 - 使用UTC时间
  if (startDate && endDate) {
    // 开始时间：当天0点0分0秒 (UTC时间)
    const [startYear, startMonth, startDay] = startDate.split('-');
    const startDateTime = new Date(Date.UTC(startYear, startMonth - 1, startDay, 0, 0, 0, 0));
    
    // 结束时间：当天23点59分59秒 (UTC时间)
    const [endYear, endMonth, endDay] = endDate.split('-');
    const endDateTime = new Date(Date.UTC(endYear, endMonth - 1, endDay, 23, 59, 59, 999));
    
    condition.create_ts = _.and([
      _.gte(startDateTime),
      _.lte(endDateTime)
    ]);
  }

  return queryOrderByCondition(condition, page, pageSize, true); // 统计时不区分产品
  
}

/**
 * 获取订单统计数据
 * @param {Object} request - 请求参数
 * @param {string} [request.schoolCode] - 学校代码
 * @param {string} [request.orderType] - 订单类型
 * @param {string} [request.startDate] - 开始日期 (YYYY-MM-DD)
 * @param {string} [request.endDate] - 结束日期 (YYYY-MM-DD)
 * @param {string} [request.date] - 指定日期 (YYYY-MM-DD)
 * @returns {Promise<Object>} 返回订单统计数据
 */
async function getOrderStatistics(request) {
  try {
    const {
      schoolCode,
      orderType,
      startDate,
      endDate,
      date
    } = request;

    console.log('获取订单统计数据请求:', request);

    // 构建基础查询条件
    let condition = {
      order_status: _.and([_.neq("待支付")]) // 排除待支付订单
    };

    // 添加学校代码筛选
    if (schoolCode) {
      condition['address.schoolCode'] = schoolCode;
    }

    // 添加订单类型筛选
    if (orderType) {
      condition["order_item.product_id"] = orderType;
    }

    // 处理日期筛选 - 使用UTC时间
    if (date) {
      // 指定日期：查询该日期的订单 (UTC时间)
      const [year, month, day] = date.split('-');
      const startDateTime = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));
      const endDateTime = new Date(Date.UTC(year, month - 1, day, 23, 59, 59, 999));
      
      condition.create_ts = _.and([
        _.gte(startDateTime),
        _.lte(endDateTime)
      ]);
    } else if (startDate && endDate) {
      // 日期范围：查询指定范围内的订单 (UTC时间)
      const [startYear, startMonth, startDay] = startDate.split('-');
      const [endYear, endMonth, endDay] = endDate.split('-');
      const startDateTime = new Date(Date.UTC(startYear, startMonth - 1, startDay, 0, 0, 0, 0));
      const endDateTime = new Date(Date.UTC(endYear, endMonth - 1, endDay, 23, 59, 59, 999));
      
      condition.create_ts = _.and([
        _.gte(startDateTime),
        _.lte(endDateTime)
      ]);
    }

    console.log('订单统计查询条件:', condition);

    // 查询订单总数
    const totalResult = await db.collection('order').where(condition).count();
    const totalOrders = totalResult.total;

    // 查询各状态订单数量
    const statusConditions = {
      ...condition,
      order_status: "已支付"
    };
    const inProgressResult = await db.collection('order').where(statusConditions).count();
    const inProgressOrders = inProgressResult.total;

    const completedConditions = {
      ...condition,
      order_status: "已完成"
    };
    const completedResult = await db.collection('order').where(completedConditions).count();
    const completedOrders = completedResult.total;

    const refundedConditions = {
      ...condition,
      order_status: _.in(["已退款", "部分退款"])
    };
    const refundedResult = await db.collection('order').where(refundedConditions).count();
    const refundedOrders = refundedResult.total;

    // 查询已领取订单数量
    const claimedConditions = {
      ...condition,
      deliver_out_user_id: _.and([
        _.neq(null),
        _.neq(""),
        _.neq(undefined)
      ])
    };
    const claimedResult = await db.collection('order').where(claimedConditions).count();
    const claimedOrders = claimedResult.total;

    // 查询未领取订单数量
    const unclaimedConditions = {
      ...condition,
      deliver_out_user_id: _.or([
        _.eq(null),
        _.eq(""),
        _.eq(undefined)
      ])
    };
    const unclaimedResult = await db.collection('order').where(unclaimedConditions).count();
    const unclaimedOrders = unclaimedResult.total;

    // 查询今日退款中订单数量
    let todayRefundingConditions = {
      ...condition,
      order_status: "退款中"
    };
    
    // 如果有日期筛选条件，则使用相同的日期范围
    if (condition.create_ts) {
      todayRefundingConditions.create_ts = condition.create_ts;
    }
    const todayRefundingResult = await db.collection('order').where(todayRefundingConditions).count();
    const todayRefundingOrders = todayRefundingResult.total;

    console.log('订单统计结果:', {
      totalOrders,
      inProgressOrders,
      completedOrders,
      refundedOrders,
      claimedOrders,
      unclaimedOrders,
      todayRefundingOrders
    });

    return {
      code: 200,
      message: "获取订单统计数据成功",
      data: {
        totalOrders,        // 订单总数
        inProgressOrders,   // 进行中订单数
        completedOrders,    // 已完成订单数
        refundedOrders,     // 已退款订单数
        claimedOrders,      // 已领取订单数
        unclaimedOrders,    // 未领取订单数
        todayRefundingOrders, // 今日退款中订单数
        queryDate: date || `${startDate} 至 ${endDate}` || '全部'
      }
    };

  } catch (error) {
    console.error("获取订单统计数据失败：", error);
    return {
      code: 500,
      message: "获取订单统计数据失败",
      data: null
    };
  }
}

module.exports = {
  getOrderList: getOrderList,
  getOrderListForManage: getOrderListForManage,
  getOrderForDetail: getOrderForDetail,
  getOrderStatistics: getOrderStatistics
};
